﻿using BCL.Tool;
using BCL.Tool.Extend;
using BCL.WPFComponent.Base;
using Devices;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Net;
namespace DevicesWPF
{
    /// <summary>
    /// UCDevicesConfig.xaml 的交互逻辑
    /// </summary>
    public partial class UCDevicesConfig : BaseShowControl
    {
        private IDevices dev;
        private UserControl devuc;
        public UCDevicesConfig()
        {
            InitializeComponent();
        }
        public UCDevicesConfig(IDevices devices)
        {
            InitializeComponent();
            dev = devices;
            this.Title = devices.Info.DisplayName;
            this.Title += " 配置".Language();
        }
        public override void LanguageBinding()
        {

        }
        public override void ReloadData(object data)
        {
            dev = (IDevices)data;
            base.ReloadData(data);
            
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            if (dev != null)
            {
                TextBlockName.Text = dev.Info.Name;
                TextBlockDisplayName.Text = dev.Info.DisplayName;
                TextBlockBrand.Text = dev.Info.Brand;
                TextBlockCode.Text = dev.Info.Code;
                textBox1.Text = dev.Config?.ManagerAddress;
                string imagepath = dev.Info.GetImageFillPath();
                if (File.Exists(imagepath))
                    this.image1.Source = File.ReadAllBytes(imagepath).ToBitmap();
                radioButton2.Checked += RadioButton2_Checked;
                radioButton1.Checked += RadioButton1_Checked;
                radioButton1.IsChecked = dev.Config.CurrentConnectType == ConnectType.Manager;
                radioButton2.IsChecked = !radioButton1.IsChecked;

                if (dev.Config != null)
                {
                    this.tabControl1.Items.Clear();
                    foreach (var item in dev.Config.ResultConfig)
                    {
                        TabItem tp = new TabItem { Header = item.Name, Tag=item, Style = (Style)this.FindResource("TabItemStyle") };
                        UCResultConfig itemconfig = new UCResultConfig(item);
                        itemconfig.ResultNameChanged += name => tp.Header = name;
                        tp.Content = itemconfig;
                        this.tabControl1.Items.Add(tp);
                    }
                    tabControl1.SelectedIndex = 0;
                }

                ///加载设备的设置页
                Assembly assembly= Assembly.GetExecutingAssembly();
                ConstructorInfo[] cinfos = assembly.GetType("DevicesWPF.UCDevices.UC" + dev.Info.Code)?.GetConstructors();
                if (cinfos != null)
                {
                    ConstructorInfo cinfo = cinfos.FirstOrDefault(o=>o.GetParameters()?.Length==1);
                    if (cinfo != null)
                    { 
                        devuc = cinfo.Invoke(new object[] { dev }) as UserControl;
                        devuc.HorizontalAlignment = HorizontalAlignment.Left;
                        devuc.VerticalAlignment = VerticalAlignment.Top;
                        if (devuc != null)
                            borderContext.Children.Add(devuc);// = devuc;
                    }
                }
            }
        }

        private void RadioButton2_Checked(object sender, RoutedEventArgs e)
        {
            stackPanel1.Visibility = Visibility.Hidden;
            borderContext.Visibility = Visibility.Visible;
        }

        private void RadioButton1_Checked(object sender, RoutedEventArgs e)
        {
            stackPanel1.Visibility = Visibility.Visible ;
            borderContext.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (this.radioButton1.IsChecked == true)
            {
                IPAddress iPAddress = null;
                if (!IPAddress.TryParse(textBox1.Text, out iPAddress))
                {
                    MessageBox.Show("请输入一个合法的IP地址");
                    return;
                }

                dev.Config.ManagerAddress = textBox1.Text;
                dev.Config.CurrentConnectType = ConnectType.Manager;
            }
            else
            {
                int error = 0;
                dev.Config= (devuc as IUCConfig)?.GetConfig(out error);
            }

            dev.Info.DisplayName = TextBlockDisplayName.Text;
            dev.Info.Name = TextBlockName.Text;
            dev.Config.AutoConnect = checkBoxAutoConnect.IsChecked == true;
            dev.Config.ResultConfig = GetConfig();
            if (dev.Config.ResultConfig == null)
            {
                MessageBox.Show("配置有错！");
                return;
            }

            if (dev.Config.AutoConnect)
                dev.Restart();
            dev.SaveConfig();
            this.MessageBoxResult = MessageBoxResult.OK;
            this.Close();
        }

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            TabItem tp = new TabItem { Header = "新建项",  Style = (Style)this.FindResource("TabItemStyle")};
            UCResultConfig itemconfig = new UCResultConfig();
            itemconfig.ResultNameChanged += name => tp.Header = name;
            tp.Content = itemconfig;
            this.tabControl1.Items.Add(tp);
            tabControl1.SelectedItem = tp;
        }

        protected virtual List<ResultConfig> GetConfig()
        {
            dev.Config.AutoConnect = checkBoxAutoConnect.IsChecked == true;

            if (this.tabControl1.Items.Count > 0)
            {
                List<ResultConfig> rcs = new List<ResultConfig>();
                foreach (TabItem item in this.tabControl1.Items)
                {
                    UCResultConfig uic = (UCResultConfig)item.Content;
                    ResultConfig rc = uic.GetResultConfig();
                    if (rc == null)
                    {
                        tabControl1.SelectedItem = item;
                        return null;
                    }
                    rcs.Add(rc);
                }
                return rcs;
            }
            return null;
        }


    }
}
